package Netty.权威指导demo.基础写法;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.util.Date;

public class TimeServer {

    public void bind(int port) throws InterruptedException {
        // 配置服务端的NIO线程组
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    //设置线程队列得到连接个数
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new TimeServerHandler());
                        }
                    });
            // 绑定端口，同步等待成功  主要用户异步操作的通知回调
            ChannelFuture f = b.bind(port).sync();
            // sync进行阻塞，等待服务端链路关闭只有main函数才退出
            f.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) throws InterruptedException {
        int port = 8080;
        new TimeServer().bind(port);
    }

    class TimeServerHandler extends ChannelInboundHandlerAdapter {

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            // 获取客户端发送过来的消息 ByteBuf类似JDK中的ByteBuffer对象，通过ByteBuf的readableBytes可以获取缓冲区可读的字节数，
            ByteBuf byteBuf = (ByteBuf) msg;
            // 根据字节数创建byte数组
            byte[] req = new byte[byteBuf.readableBytes()];
            // 通过ByteBuf的readBytes方法将缓冲区中的字节数组复制到新建的byte数组中
            byteBuf.readBytes(req);
            // 最后通过String构造函数获取请求消息
            String body = new String(req, "UTF-8");
            // 打印客户端消息
            System.out.println("服务端收到消息 : " + body);
            // 组装服务端发送到客户端消息 如果是QUERY TIME ORDER则回复消息
            String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER";
            ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
            // 发送消息 通过ChannelHandlerContext的write方法异步发送应答消息给客户端
            ctx.write(resp);
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) {
            // flush方法，作用是将消息发送队列中的消息写入到SocketChannel中
            // 从性能角度考虑，为了防止频繁地唤醒Selector进行消息发送，Netty的write方法并不直接将消息写入SocketChannel中
            // 调用write方法只是把待发送的消息放到缓冲数组中，再再通过调用flush 将发送缓冲区中的消息全部写到SocketChannel中
            ctx.flush();
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            ctx.close();
        }
    }

}
